<?php
namespace libraries;

use enums\HttpServerEnums;
use enums\ServiceEnums;
/*
 * 用redis实现跨服务器session
 * 注意需要安装phpredis模块
 *
 * 日期:2012-07-23 22:55:00
 */
class RedisSession implements \Phalcon\Di\InjectionAwareInterface 
{
    private $expire = 86400;
 // 过期时间
    private $sid;
 // session id
 //   private $session_folder;
 // session目录 
    private $cookie_name = HttpServerEnums::SESSION_KEY;
 // cookie的名字
    private $redis;
 // redis连接
    private $cache;
   
    private $sessionData = null;
   
    private $_di;
   
    private $_cookies;
 // 缓存session
 //   private $expireAt;
 // 过期时间
 //   private $session_prefix;

    
    /*
     * 初始化
     * 参数
     * $redis:php_redis的类实例
     * $cookie_name:cookie的名字
     * $session_id_prefix:sesion id的前缀
     */
    public function __construct( $di )
    {
    	$this->_di = $di;
    	
    	if( isset( $di->redisSession ))
    	{
       		$this->redis = $di->redisSession;
    	}
    	$this->_cookies = $di->get( ServiceEnums::SERVICE_COOKIES );
    	
    	$this->sessionData = null;
    }

    
    /*
     * 设置多个session的值
     * 参数
     * $array:值
     */
    public function setMutil($array)
    {
//     	$this->checkCookie();
    	
        $this->redis->hMset( $this->getId(), $array );
    }
    
    public function setId( $id )
    {
        $this->sid = $id;
        $this->redis->expire( $this->sid, $this->expire );
    }
    
    /*
     * 获取sessionid
     */
    public function getId()
    {
    	$this->checkCookie();
    	
        return $this->sid;
    }

    private function checkCookie()
    {
    	if( empty($_COOKIE[ HttpServerEnums::SESSION_KEY ]) )
    	{//libphp php-fpm .etc
    		
	    	$strSessionID = '' . sprintf('%04X%04X%04X%04X%04X%04X%04X%04X', mt_rand(0, 65535), mt_rand(0, 65535),
	    			mt_rand(0, 65535), mt_rand(16384, 20479), mt_rand(32768, 49151),
	    			mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(0, 65535));
	    	 	    	 
	    	$this->setId( $strSessionID );
	    	$this->_cookies->set( HttpServerEnums::SESSION_KEY, $strSessionID );
    	}
    	else
    	{    	
    		$cookie = $this->_cookies->get( HttpServerEnums::SESSION_KEY );
    		
    		if( $cookie->isUsingEncryption() )
    		{//phalcon中的bug 导致getValue()在加密状态时取出的数据是错误的
    			$crypt = $this->_di->get( 'crypt' );
    			$strID = $crypt->decryptBase64( $_COOKIE[ HttpServerEnums::SESSION_KEY ] );
    		}
    		else 
    		{
    			$strID = $cookie->getValue();
    		}

    		$this->setId( $strID );
    	}
    	 
    }
    
    /*
     * 设置session的值
     * 参数
     * $key:session的key
     * $value:值
     */
    public function set( $key, $value )
    {
        if( !$value )
            return;
        
// 		$this->checkCookie();
		
        return $this->redis->hSet($this->getId(), $key, serialize($value) );
    }
    
    /*
     * 是否存在$key
     * $key:session的key
     */
    public function has($key)
    {
//     	$this->checkCookie();
        $keyOfval = $this->redis->hGet( $this->getId(), $key );
        if( $keyOfval )
            return true;
        else
            return false;
    }

    /*
     * 设置session的值为对象
     * 参数
     * $key:session的key
     * $object:对象
     */
    public function setObject($key, $object)
    {
//     	$this->checkCookie();
        return $this->redis->hSet($this->getId(), $key, serialize($object));
    }

    /*
     * 获取全部session的key和value
     * @return: array
     */
    public function getAll()
    {
//     	$this->checkCookie();
    	
        return $this->redis->hGetAll( $this->getId() );
    }

    /*
     * 获取一个session的key和value
     * @return: array
     */
    public function get($key)
    {
        if( !$key )
            return;
        
//         $this->checkCookie();
        
        $result = $this->redis->hGet( $this->getId(), $key);
        if( $result )
        {
            return unserialize( $result );
        }
        return null;
    }

    /*
     * 获取session的值为对象
     * 参数
     * $key:session的key
     * $value:cookie的名字
     */
    public function getObject($key)
    {
//     	$this->checkCookie();
    	
        return unserialize($this->redis->hGet($this->getId(), $key));
    }

    /*
     * 从缓存中获取一个session的key和value
     * @return: array
     */
    public  function getFromCache($key)
    {
    	
        if (! isset($this->cache)) 
        {
            $this->cache = $this->getAll();
        }
        
        return $this->cache[$key];
    }

    /*
     * 删除一个session的key和value
     * @return: array
     */
    public function del($key)
    {
//     	$this->checkCookie();
    	
        return $this->redis->hDel($this->getId(), $key);
    }

    /*
     * 删除所有session的key和value
     * @return: array
     */
    public function delAll()
    {
//     	$this->checkCookie();
    	
        return $this->redis->delete($this->getId());
    }
    
    /**
     * {@inheritdoc}
     */
    public function destroy($sessionId = null)
    {
//     	$this->checkCookie();
    	
        return $this->redis->del( $this->getId() );
    }
    
    /**
     * {@inheritdoc}
     * @param string $maxLifetime
     */
    public function gc($maxLifetime)
    {
        return true;
    }
    
	/* (non-PHPdoc)
	 * @see \Phalcon\Di\InjectionAwareInterface::setDI()
	 */
	public function setDI(\Phalcon\DiInterface $dependencyInjector) 
	{
		// TODO Auto-generated method stub
		$this->_di = $dependencyInjector;	
	}

	/* (non-PHPdoc)
	 * @see \Phalcon\Di\InjectionAwareInterface::getDI()
	 */
	public function getDI() 
	{
		// TODO Auto-generated method stub
		return $this->_di;
	}

}
?>